<template>
  <div>
    <!-- 按钮组 -->
    <div class="button-group">
      <button
        :class="['button', { 'active': activeTab === 'statistics' }]"
        @click="changeTab('statistics')"
      >
        统计
      </button>
      <button
        :class="['button', { 'active': activeTab === 'details' }]"
        @click="changeTab('details')"
      >
        明细
      </button>
    </div>

    <!-- 统计内容 -->
    <div v-if="activeTab === 'statistics'" class="tab-content">
      <el-card class="chart-card">
        <div slot="header">30天对话量:</div>
        <div ref="dialogChart" style="height: 400px;"></div>
      </el-card>
      <el-card class="chart-card" style="margin-top: 20px">
        <div slot="header">7天知识库上传文件情况:</div>
        <div ref="fileUploadChart" style="height: 400px;"></div>
      </el-card>
    </div>

    <!-- 明细内容 -->
    <div v-else-if="activeTab === 'details'" class="tab-content">
      <!-- 过滤工具栏 -->
      <div class="filter-bar">
        <div class="filter-group">
          <el-date-picker
            v-model="filter.range"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
          <el-input
            v-model="filter.query"
            placeholder="提问内容"
            clearable
            style="width: 30%;"
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
          <el-tooltip class="item" effect="dark" content="查询" placement="top">
            <el-button
              icon="el-icon-search"
              circle
              @click="handleSearch"
              style="margin-left: 20px"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="重置" placement="top">
            <el-button
              icon="el-icon-refresh"
              circle
              @click="handleClear"
            >
            </el-button>
          </el-tooltip>
        </div>

        <div class="action-buttons">
          <el-button type="primary" style="color: black;background: white;border-color: #DDDEDF;border-radius: 7px;" size="small" @click="exportSelected">
            导出选中
          </el-button>
<!--          <el-button type="success" style="background: #5A47E5;border-color: #5A47E5;border-radius: 7px;" size="small" @click="downExcel">-->
<!--            导出全部-->
<!--          </el-button>-->
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        stripe
        size="small"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="60"
          align="center">
        </el-table-column>
        <el-table-column prop="kb_ids" label="知识库id" width="320">
          <template slot-scope="scope">
            <div v-for="(value) in scope.row.kb_ids">{{ value }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="query" label="问题"></el-table-column>
        <el-table-column prop="result" label="答案"></el-table-column>
        <el-table-column prop="model" label="模型"></el-table-column>
        <el-table-column prop="timestamp" label="时间"></el-table-column>

<!--        <el-table-column label="操作" width="170" align="center">-->
<!--          <template slot-scope="scope">-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :current-page="currentPage"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="loadTableData"
      />
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { qainfo,totalStatus,qadetail,exportData } from "@/api/dataManage/index";

export default {
  data() {
    return {
      activeTab: 'statistics',
      // 筛选条件
      filter: {
        range: '',
        query: ''
      },
      // 表格数据
      tableData: [],
      loading: false,
      total: 0,
      currentPage: 1,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 当前选中行
      multipleSelection: [],
    };
  },
  mounted() {
    this.initCharts();
    this.loadTableData();
  },
  methods: {
    // 加载表格数据
    loadTableData() {
      qadetail({
        "query": this.filter.query,
        "time_start": this.filter.range ? this.format(this.filter.range[0],'yyyy-MM-dd') :'',
        "time_end": this.filter.range ? this.format(this.filter.range[1],'yyyy-MM-dd') :'',
        "page_id": this.queryParams.pageNum,
        "page_limit": this.queryParams.pageSize,
      }).then(res => {
        this.tableData = res.data.qa_infos
        this.total = res.data.total_count
      })
    },

    // 处理选中行变化
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 手动触发搜索
    handleSearch() {
      this.currentPage = 1;
      this.loadTableData();
    },
    handleClear(){
      this.filter = {}
      this.currentPage = 1;
      this.loadTableData();
    },
    // 导出选中
    exportSelected() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条记录');
        return;
      }
      var qaIds = []
      this.multipleSelection.forEach(row => {
        qaIds.push(row.qa_id)
      })
      exportData({
        "qa_ids": qaIds,
        "save_to_excel": true
      }).then(data =>{
        console.log("aaaa1",data.headers)
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data],{type: 'application/octet-stream'}), '导出数据.xlsx')
        }else{
          let url = window.URL.createObjectURL(new Blob([data],{type: 'application/octet-stream'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', '导出数据.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },
    // 切换标签页
    changeTab(tabName) {
      this.activeTab = tabName;
      if(tabName === 'statistics'){
        this.$nextTick(()=>{
          this.initCharts();
        })
      }else if(tabName === 'details'){
        this.$nextTick(()=>{
          this.loadTableData();
        })
      }
    },

    // 初始化图表
    initCharts() {
      this.getQaInfo()
      this.getTotalStatus()
    },
    getQaInfo(){
      qainfo({
        "only_need_count": true,
        "time_start": '',
        "time_end": ''
      }).then(res => {
        this.chartQaInfo(res.data)
      })
    },
    chartQaInfo(data){
      const dialogChart = echarts.init(this.$refs.dialogChart);

      var xDataList = []
      var valueList = []
      Object.keys(data).forEach(key => {
        xDataList.push(key)
        valueList.push(data[key])
      });

      const dialogOption = {
        tooltip: {},
        xAxis: {
          type: 'category',
          data: xDataList,
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: valueList,
            type: 'line',
            itemStyle: { color: '#409EFF' },
          },
        ],
      };
      dialogChart.setOption(dialogOption);
    },
    getTotalStatus(){
      totalStatus().then(res => {
        this.chartTotalStatus(res.data)
      })
    },
    chartTotalStatus(data){
      const fileUploadChart = echarts.init(this.$refs.fileUploadChart);

      var xDataList = []
      var valueList1 = []
      var valueList2 = []
      var valueList3 = []
      Object.keys(data).forEach(key => {
        xDataList.push(key)
        if(data[key].green){
          valueList1.push(data[key].green)
        }else{
          valueList1.push(0)
        }

        if(data[key].gray){
          valueList2.push(data[key].gray)
        }else{
          valueList2.push(0)
        }

        if(data[key].red){
          valueList3.push(data[key].red)
        }else{
          valueList3.push(0)
        }
      });
      const fileUploadOption = {
        tooltip: {},
        xAxis: {
          type: 'category',
          data: xDataList,
        },
        yAxis: {
          type: 'value',
        },
        legend: {
          data: ['green', 'gray', 'red']
        },
        series: [
          {
            name: 'green',
            data: valueList1,
            type: 'line',
            itemStyle: { color: '#67C23A' },
          },
          {
            name: 'gray',
            data: valueList2,
            type: 'line',
            itemStyle: { color: 'gray' },
          },
          {
            name: 'red',
            data: valueList3,
            type: 'line',
            itemStyle: { color: 'red' },
          }
        ],
      };

      fileUploadChart.setOption(fileUploadOption);
    },
    format (thistime,fmt) {
      let $this = new Date(thistime)
      var o = {
        "M+": $this.getMonth() + 1, // 月份
        "d+": $this.getDate(), // 日
        "h+": $this.getHours(), // 小时
        "m+": $this.getMinutes(), // 分
        "s+": $this.getSeconds(), // 秒
        "q+": Math.floor(($this.getMonth() + 3) / 3), // 季度
        "S": $this.getMilliseconds() // 毫秒
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, ($this.getFullYear() + "").substr(4 - RegExp.$1.length));
      for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      return fmt;
    },
  },
};
</script>

<style scoped lang="scss">
.button-group {
  display: flex;
  background-color: #f0f2f5;
  border-radius: 8px;
  overflow: hidden;
  margin: 20px 0 20px 20px;
  width: 180px;
  height: 40px;
}

.button {
  border: none;
  background-color: transparent;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #606266;
  font-size: 14px;
  font-weight: normal;
  height: 30px;
  width: 80px;
  margin: 5px;
  border-radius: 5px;
}

.button:hover {
  background-color: #e6e8eb;
}

.button.active {
  background-color: white;
  color: #409EFF;
  font-weight: bold;
}

.tab-content {
  padding: 20px;
}

/* 明细模块新增样式 */
.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  width: 80%;
}

.action-buttons {
  display: flex;
  gap: 10px;
}
</style>
